package com.zys.utils;

import com.qiniu.util.Auth;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;


/**
 * 七牛云工具类
 */
public class QiniuUtils {
  private static final String accessKey = "Q3xrlPyuIJ11BxNrSit9jE5ZdkHHsyDnscowO7r3"; // 公钥
  private static final String secretKey = "qthK1JYGvQiRHct1mgaB-Ysw1inagHDKsiyvFUWu"; // 私钥
  private static final String bucket = "zysgradution-space-1";                        // 存储空间
  private static final Configuration cfg = new Configuration(Zone.zone2());           // 所处地域
  private static final UploadManager uploadManager = new UploadManager(cfg);          // 上传管理对象
  private static final Auth auth = Auth.create(accessKey, secretKey);                 // 验证对象

  /**
   * 上传文件到七牛云
   *
   * @param filePath
   * @param fileName
   */
  public static void upload2Qiniu(String filePath, String fileName) {
    String upToken = auth.uploadToken(bucket);
    try {
      Response response = uploadManager.put(filePath, fileName, upToken);
      //解析上传成功的结果
      new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    } catch (QiniuException ex) {
      Response r = ex.response;
      try {
        System.err.println(r.bodyString());
      } catch (QiniuException ex2) {
        //ignore
      }
    }
  }

  // 上传文件
  public static void upload2Qiniu(byte[] bytes, String fileName) {
    // 默认不指定 key 的情况下, 以文件内容的 hash 值作为文件名
    String upToken = auth.uploadToken(bucket);
    try {
      Response response = uploadManager.put(bytes, fileName, upToken);
      //解析上传成功的结果
      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
      System.out.println(putRet.key);
      System.out.println(putRet.hash);
    } catch (QiniuException ex) {
      Response r = ex.response;
      System.err.println(r.toString());
      try {
        System.err.println(r.bodyString());
      } catch (QiniuException ex2) {
        //ignore
      }
    }
  }

  // 删除文件
  public static void deleteFileFromQiniu(String fileName) {
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
      bucketManager.delete(bucket, fileName);
    } catch (QiniuException ex) {
      //如果遇到异常，说明删除失败
      System.err.println(ex.code());
      System.err.println(ex.response.toString());
    }
  }
}
